<?php
namespace app\bee\controller;
use think\Controller;
use think\Cache;
use \DOMDocument;
use \DateTime;

class Adidas extends BeeController {
  
  const CATEGORY_ID = 849;
  const BRAND_ID = 357;
  const UPLOAD_PATH = UPLOAD_PATH;
  
  public function index(){
    $productsInfo = $this->getProductsInfo();
    
    if (is_array($productsInfo['products']) && !empty($productsInfo['products'])) {
      $downloadImage = $this->downloadImage($productsInfo['products'][0]['original_img']);
      $productsInfo[0]['original_img'] = $downloadImage;
    } else {
      var_dump(is_array($productsInfo['products']), empty($productsInfo['products']));
    }
    
    $this->assign('products', $productsInfo['products']);
    return view();
  }
  
  private function getProductsInfo() {
    $url = "http://www.adidas.com/us/best_sellers?sz=120&start=0";
    $total_count = 0;
    $products = array();
    if (Cache::get('adidas_response')) {
      $response = Cache::get('adidas_response');
    } else {
      $response = $this->request($url);
      Cache::set('adidas_response', $response, 3600);
    }
    
    $doc = new DOMDocument();
    libxml_use_internal_errors(true);
    $doc->loadHTML($response);
    // var_dump($html);
    $main_elements = $doc->getElementsByTagName("div");
    $count = 0;
    $data = array();
    foreach ($main_elements as $key => $item) {
      // var_dump($key);
      // var_dump($item->getAttribute('class'));
      if (strpos($item->getAttribute('class'), 'page-heading') !== false) {
        $ps = $item->getElementsByTagName('p');
        foreach ($ps as $p) {
          $total_count = intval(substr(trim($p->nodeValue), 1));
        }
        // var_dump('$p', $p);
        continue;
        // break;
      }
      if (strpos($item->getAttribute('class'), 'hockeycard') !== false) {
        $data['goods_sn'] = substr($item->getAttribute('id'), strlen('product-'));
        $imgs = $item->getElementsByTagName('img');
        foreach ($imgs as $img) {
          $data['goods_name'] = substr($img->getAttribute('alt'), strlen('adidas - '));
          $data['original_img'] = $img->getAttribute('data-src');
          $data['product_price'] = $img->getAttribute('data-salespricevalue');
        }
        $products[] = $data;
        
        // var_dump($item);
//         foreach ($spans as $span) {
//           if ($span->getAttribute('class') == "title") {
//             echo nl2br($item->getAttribute('id') . ' ' . $span->nodeValue . PHP_EOL);
//           }
//         }
        
      }
    }
    $result = [
      'products' => $products,
      'total_count' => $total_count,
    ];
    // var_dump($result['total_count']);
    return $result;
  }
}